<template>
    <el-card shadow="never" style=" width: 100%; border-radius: 4px;">
        <div class="search-container">
            <p class="textitem flex-start" style="font-size: 18px; margin-bottom: 16px;" placeholder="请输入关键字">
            <h2>{{ isEdit ? '修改服务项目' : '新增服务项目' }}</h2>
            </p>
        </div>
        <!-- 分割线 -->
        <div class="line" style="border-top: 1px solid #e4e7ed; margin: 0 16px;"></div>


        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" style="padding: 24px;">
            <div class="form-row">
                <el-form-item label="项目名称">
                    <el-input v-model="formData.name" style="width: 200px; height: 40px;margin-right: 40px;"
                        placeholder="请输入" />
                </el-form-item>

                <el-form-item label="服务次数" prop="orgName">
                    <el-input v-model="formData.count" style="width: 200px; height: 40px;   margin-right: 15px;"
                        placeholder="请输入" />
                    <!-- 这部分没写完------------------------------------------------ -->
                    <!-- <el-radio size="large" style="fill: #2984F8;">不限次数</el-radio> -->
                    <el-radio-group>

                    </el-radio-group>
                </el-form-item>

            </div>

            <div class="form-row">
                <el-form-item label="项目类型">
                    <el-input v-model="formData.type" style="width: 200px; height: 40px;margin-right: 40px;"
                        placeholder="免费项目、付费项目，二选一" />
                </el-form-item>

                <el-form-item label="项目原价">
                    <el-input v-model="formData.price" style="width: 200px; height: 40px;margin-right: 15px;"
                        placeholder="请输入" />
                    <span style="color: #999;">元</span>
                </el-form-item>
            </div>


            <div class="form-row">
                <el-form-item label="服务介绍">
                    <el-input type="textarea" v-model="formData.intro" :rows="4" style="width: 578px; height: 120px;"
                        placeholder="请输入" />
                </el-form-item>
            </div>
            <div class="line" style="border-top: 1px solid #e4e7ed; margin: 0 16px;"></div>
            <!-- 操作按钮 -->
            <div class="form-row" style="justify-content: flex-start; margin-top: 24px;">
                <el-button type="primary" @click="handSave">保存</el-button>
                <el-button @click="handBack" style="margin-left: 12px;">返回</el-button>
            </div>
        </el-form>
    </el-card>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { ElForm, ElMessage, ElButton, ElInput } from 'element-plus';
import { addServiceItemsApi, detailServiceItemsApi, updateServiceItemsApi } from '@/api/service';
import { useRoute, useRouter } from 'vue-router';
//路由实例
const route = useRoute();
const router = useRouter();

// 表单引用
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
// 表单数据
const formData = ref({
    serviceId: '',
    name: '',
    count: '',
    type: '',
    price: '',
    intro: ''
});

// 表单校验规则
const formRules = ref<any>({
    name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' }
    ],
    count: [
        { required: true, message: '请输入服务次数', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入项目原价', trigger: 'blur' },
        { type: 'number', message: '请输入数字', trigger: 'blur' }
    ]
});

//获取机构的ID(从路由传参传)
const serviceId = computed(() => {
    return route.params._id as string
})
//是否为编辑模式
const isEdit = computed(() => !!serviceId.value)

// 页面加载时初始化数据
onMounted(() => {
    if (isEdit.value) {
        // 获取一个居民项目服务详情 
        detailServiceItemsApi({ _id: serviceId.value })
            .then(res => {
                if (res.code === 200) {
                    formData.value = {
                        ...formData.value,
                        ...res.data,
                    };
                }
            })
            .catch(err => {
                console.error('获取机构详情失败:', err);
            });
    } else {
        // 新增模式生成机构ID
        formData.value.serviceId = generateserviceId()
    }
})
//新增生成的ID号
function generateserviceId() {
    const timestamp = Date.now()
    return timestamp.toString()
}
// 保存表单
const handSave = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            // 判断是新增还是修改
            if (isEdit.value) {
                // 调用修改接口
                updateServiceItemsApi(formData.value)
                    .then(res => {
                        if (res.code === 200) {
                            ElMessage.success('机构修改成功');
                            router.push('/data/serviceItem/list');
                        } else {
                            ElMessage.error(res.message || '修改失败，请重试');
                        }
                    })
                    .catch(err => {
                        console.error('修改机构失败:', err);
                        ElMessage.error('网络错误，修改失败');
                    });
            } else {
                // 调用新增接口
                addServiceItemsApi(formData.value)
                    .then(res => {
                        if (res.code === 200) {
                            ElMessage.success('机构新增成功');
                            router.push('/data/serviceItem/list');
                        } else {
                            ElMessage.error(res.message || '新增失败，请重试');
                        }
                    })
                    .catch(err => {
                        console.error('新增机构失败:', err);
                        ElMessage.error('网络错误，新增失败');
                    });
            }
        }
    });
};
// 返回列表页
const handBack = () => {
    router.push('/data/serviceItem/list');
};




</script>

<style scoped lang="scss">
.search-container {
    padding: 10px 0;
    background: #fff;
    border-radius: 4px;
}



.textitem {
    position: relative;
    padding-left: 12px;
    /* 给蓝色小条留出空间 */
}

.flex-start {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.textitem::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 20px;
    background-color: rgba(41, 132, 248, 1);
    border-radius: 8px;
}


.form-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    >.el-form-item {
        margin-right: 0;
        margin-left: 0;

        &:not(:first-child) {
            margin-left: 24px;
        }
    }

    &:last-child {
        margin-bottom: 0;
    }
}





.el-input {
    --el-input-bg-color: #fff;
    --el-input-border-color: #dcdfe6;
    --el-input-hover-border-color: #c0c4cc;
}
</style>